<template>
    <div>
        <span @click="handleVisible(true)" v-if="btnVisible">
            <!-- 自定义选择分账方按钮 -->
            <slot name="btn" :selectedRow="selectedRow" :ids="ids" :title="title">
                <el-button
                    class="custom-text-button"
                    type="primary"
                    text
                    :disabled="disabled || exclude.length >= 20"
                    icon="Plus">
                    {{ title }} </el-button
                ><span @click.stop class="custom-text-button-tip"
                    >（最多选择19个<span v-if="exclude.length > 1">，已选{{ exclude.length - 1 }}个</span>）</span
                >
            </slot>
        </span>
        <el-dialog
            class="sub_account_dialog"
            :class="{ 'general-multi-template-dialog': isMulti }"
            align-center
            :title="title"
            v-model="visible"
            width="80%"
            @close="closeCallback()">
            <div class="sub_account_dialog_header">
                <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                    <el-row justify="space-between" :gutter="16">
                        <el-col :span="6">
                            <el-form-item prop="login">
                                <el-input
                                    v-model.trim="form.login"
                                    clearable
                                    placeholder="输入主体名称或登录号查询"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- todo:商户ID 门店ID-->
                        <el-col :span="6">
                            <el-form-item prop="tenant">
                                <el-input
                                    v-model.trim="form.tenant"
                                    clearable
                                    placeholder="输入商户ID或商城名称查询"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item prop="shop">
                                <el-input
                                    v-model.trim="form.shop"
                                    clearable
                                    placeholder="输入门店ID或门店名称查询"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col class="header-search-form" :span="6">
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                            <el-button @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-table
                v-loading="loading"
                :data="tableList"
                @selection-change="handleSelectionChange"
                style="margin-top: 20px"
                height="458"
                class="choose-sub-table choose-sub-general-table"
                ref="multipleTableRef">
                <el-table-column v-if="isMulti" type="selection" :selectable="selectableHandle" width="55" />
                <el-table-column v-for="{ prop, ...rest } in tableColumnsCopy" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <template v-if="prop === 'cardName'">
                            {{ row?.cardName || '-' }}<br />{{ row?.loginNo }}
                        </template>
                        <template v-if="prop === 'corpRelation'">
                            <span v-for="item in row?.corpRelation" :key="item.corpId">
                                <span>商户ID：{{ item.corpId }}</span
                                ><br />
                                <span>商城名称：{{ item.corpName }}</span
                                ><br />
                            </span>
                            <span v-if="!row?.corpRelation || !row?.corpRelation?.length">-</span>
                        </template>
                        <template v-if="prop === 'shopRelation'">
                            <span v-for="item in row?.shopRelation" :key="item.shopId">
                                <span>门店ID：{{ item.shopId }}</span
                                ><br />
                                <span>门店名称：{{ item.shopName }}</span
                                ><br />
                            </span>
                            <span v-if="!row?.shopRelation || !row?.shopRelation?.length">-</span>
                        </template>
                        <el-button
                            class="selected-btn"
                            v-if="prop === 'operation'"
                            size="small"
                            @click="handleSelect(row)"
                            :disabled="selectedRow?.id == row.id">
                            {{ selectedRow?.id == row.id ? '已选择' : '选择' }}</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="custom-page">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
            <template #footer v-if="isMulti">
                <div style="flex: auto" class="custom-footer">
                    <div class="selected-total">
                        还可以再添加<span>{{ 20 - exclude.length }}</span
                        >个， 已选中<span>{{ ids.length }}</span
                        >个
                    </div>
                    <div>
                        <el-button plain @click="handleVisible(false)">取消</el-button>
                        <el-button type="primary" @click="handleConfirm">确认</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { cloneDeep, isEmpty } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import request from '@/request';
import Pagination from '@/components/Pagination.vue';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm']);
const props = defineProps({
    btnVisible: {
        type: Boolean,
        default: true
    },
    // 单选/多选，默认单选
    isMulti: {
        type: Boolean,
        default: true
    },
    // 是否禁用
    disabled: {
        type: Boolean,
        default: false
    },
    // 单选选择后是否关闭窗口
    selectClose: {
        type: Boolean,
        default: true
    },
    // 排除的ids
    exclude: {
        type: Array,
        default: () => [] // 需要传数据自身，所以算总数的时候需减1
    },
    // value如果是单选的话结构至少包含id,{id: '商品ID'}，如果是多选为商品集合['商品id1']
    value: {
        type: [Number, String, Object, Array],
        default: () => null
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 查询表格 start ---------------------------------- */
const form = reactive({
    page: 1,
    perPage: 10,
    login: '',
    tenant: null,
    shop: null
});
const formClone = cloneDeep(form); // 查询表单备份
const formRef = ref();
let shopList = reactive([]); // 店铺下拉列表
let loading = ref(false);

const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = reactive([
    { label: '类型', prop: 'accountTypeName', width: '100' },
    { label: '主体名称/登录号', prop: 'cardName', minWidth: '150', showOverflowTooltip: true },
    { label: '关联商户', prop: 'corpRelation', minWidth: '150', showOverflowTooltip: true },
    { label: '关联门店', prop: 'shopRelation', minWidth: '150', showOverflowTooltip: true }
]);
const tableColumnsCopy = computed(() => {
    const cols = cloneDeep(tableColumns);
    if (!props.isMulti) {
        cols.push({ label: '操作', prop: 'operation', width: '100', fixed: 'right' });
    }
    return cols;
});
/* ---------------------------------- 查询表格 end ---------------------------------- */

let selectedRow = reactive({}); // 已选中
const multipleTableRef = ref();
let ids = reactive([]); // 多选的ids
let objs = reactive([]); // 多选的objs
let idsClone = reactive([]); // 多选的ids
watch(
    () => props.value,
    val => {
        if (props.isMulti) {
            ids.length = 0;
            idsClone.length = 0;
            Object.assign(ids, val || []);
            Object.assign(idsClone, val || []);
            return;
        }
        if (isEmpty(val)) {
            const keys = Object.keys(selectedRow);
            let obj = {};
            keys.forEach(item => {
                obj[item] = null;
            });
            Object.assign(selectedRow, obj);
            return;
        }
        let row = { id: val };
        Object.assign(selectedRow, row);
    },
    {
        immediate: true,
        deep: true
    }
);

const toggleRowSelection = rows => {
    rows.forEach(item => {
        multipleTableRef?.value?.toggleRowSelection(item);
    });
};

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
let visible = ref(false);
let isClose = ref(true);
// 展示隐藏
const handleVisible = (isVisible = false) => {
    if (props.disabled) {
        return;
    }
    if (props.exclude.length > 19) {
        return;
    }
    if (!isVisible) {
        multipleTableRef.value?.clearSelection();
    }
    visible.value = isVisible;
    if (visible.value) {
        isClose.value = true;
        searchHandler();
    }
};
const closeCallback = visible => {
    // 关闭后重置表格
    // multipleTableRef.value?.clearSelection();
    formRef.value.resetFields();
    Object.assign(form, cloneDeep(formClone));
    if (isClose.value) {
        ids.length = 0;
        Object.assign(ids, cloneDeep(idsClone));
    }
    isClose.value = false;
    // searchHandler();
};
const title = computed(() => {
    return `${selectedRow?.id || props.value?.length ? (props.isMulti ? '继续' : '重新') : ''}选择${
        selectedRow?.id || props.value?.length ? '' : '分账方'
    }`;
});
/* ---------------------------------- 控制弹窗 end ---------------------------------- */

const handleSelect = row => {
    if (props.selectClose) {
        // const keys = Object.keys(selectedRow);
        // let obj = {};
        // keys.forEach(item => {
        //     obj[item] = null;
        // });
        // Object.assign(selectedRow, row);
        handleVisible(false);
    } else {
        // Object.assign(selectedRow, row);
    }
    Object.assign(selectedRow, row);
    emit('handle-confirm', row);
};
/**
 * accountType=2 且 accountStatus = 8 9 10 13 任意一种就不让选
 */
const selectableHandle = ({ accountType, accountStatus } = {}) => {
    if (accountType === 2 && ![8, 9, 10, 13].includes(accountStatus)) return false;
    return true;
};
const handleSelectionChange = val => {
    // ids
    if (!visible.value) {
        return;
    }
    nextTick(() => {
        const selectList = val.map(item => item.id);
        const selectObjList = cloneDeep(val);
        // 未选中的值
        const notSelectedList = tableList.reduce((prev, { id }) => {
            if (!selectList.includes(id)) {
                prev.push(id);
            }
            return prev;
        }, []);
        // todo:选中没选中的值
        // 过滤掉取消选中的值
        const idList = ids.filter(item => !notSelectedList.includes(item));
        // 过滤掉取消的值和不更新已存在的值
        const objsList = objs.filter(item => !notSelectedList.includes(item.id));
        const selectObjListFilter = selectObjList.filter(item => !ids.includes(item.id));
        // 选中的详细ids
        ids.length = 0;
        Object.assign(ids, [...new Set([...idList, ...selectList])]);
        // 选中的集合详细值
        objs.length = 0;
        Object.assign(objs, [...new Set([...objsList, ...selectObjListFilter])]);
    });
};

// 确认按钮
const handleConfirm = async () => {
    if (ids.length < 1) {
        ElMessage({
            type: 'error',
            message: '请先选择分账方'
        });
        return;
    }
    if (props.exclude.length + ids.length > 20) {
        ElMessage({
            type: 'error',
            message: '已选择的分账方总数超过了19个'
        });
        return;
    }
    isClose.value = false;
    emit('handle-confirm', objs);
    handleVisible(false);
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    Object.assign(form, formClone);
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryListHandler();
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryListHandler();
};
/**
 * 分页查询
 */
const queryListHandler = async () => {
    loading.value = true;
    const { data } = await request('bhtAccountList', { ...form, excludeLoginNos: props.exclude });
    // const data = {};
    tableList.length = 0;
    Object.assign(tableList, data?.data || []);
    totalCount.value = data.total;
    nextTick(() => {
        if (props.isMulti) {
            multipleTableRef.value?.clearSelection();
            toggleRowSelection(tableList.filter(item => ids.includes(item.id)));
        }
        loading.value = false;
    });
};

// 获取店铺
// const getshopList = async () => {
//     const { data } = await request('getshopList');
//     shopList.length = 0;
//     const list = data.list.map(item => {
//         item.shopInfoText = item?.shopInfo?.shopName;
//         return item;
//     });
//     list.unshift({ shopName: '全部店铺', shopId: 0 });
//     Object.assign(shopList, list);
// };

onMounted(() => {
    // getshopList();
    // searchHandler();
});

defineExpose({
    handleVisible
});
</script>

<style lang="scss">
.sub_account_dialog {
    max-width: 1100px;
    min-width: 900px;
    & > .el-dialog__header {
        box-sizing: border-box;
        padding: 15px 24px !important;
    }
    .el-table {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
    }
    /* min-height: 570px; */

    .el-table th.el-table__cell {
        padding: 8px 0;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #33302d;
    }
    .el-table .el-table__cell {
        padding: 14px 0;
    }
    .el-dialog__title {
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #33302d;
    }
    .sub_account_dialog_header .el-form-item .el-input__wrapper,
    .custom-page .zw-pagination .el-input__wrapper {
        box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
    }
}
.general-multi-template-dialog {
    .el-table th.el-table__cell {
        padding: 8px 0;
    }
}
</style>
<style lang="scss" scoped>
.custom-text-button {
    margin-top: -2px;
    padding: 0 !important;
    &.is-text:not(.is-disabled):hover,
    &.is-text:not(.is-disabled):focus {
        background-color: transparent !important;
        padding: 0 !important;
    }
    &-tip {
        /* font-size: 12px; */
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
    }
}
.sub_account_dialog {
    &_header {
        width: 100%;
        .el-form > div {
            flex-wrap: nowrap;
        }
        .header-search-form {
            text-align: right;
            :deep {
                .el-button {
                    padding: 8px 18px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #33302d;
                    & + .el-button {
                        margin-left: 8px;
                    }
                }
                .el-button--primary {
                    color: #fff;
                }
            }
        }
    }
    .center-operation {
        padding: 20px 0;
        display: flex;
        border-bottom: 1px solid #eaeaea;
        justify-content: space-between;
    }
    .selected-btn {
        padding: 5px 11px;
        color: #33302d;
        border: 1px solid #eaeaea;
        font-family: PingFangSC-Regular, PingFang SC;
        font-size: 12px;
        font-weight: 400;
        &.is-disabled,
        &.is-disabled:hover,
        &.is-disabled:focus {
            color: var(--el-button-disabled-text-color);
        }
    }
    .custom-page {
        height: auto;
        overflow: hidden;
    }
    .custom-footer {
        flex: 1 1 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        :deep {
            .el-button {
                padding: 8px 18px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
                & + .el-button {
                    margin-left: 8px;
                }
            }
            .el-button--primary {
                color: #fff;
            }
        }
    }
    .selected-total {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        span {
            margin: 0 4px;
            color: #ff6b00;
        }
    }
}
</style>
